<?php

namespace app\merchant\job;

use app\common\model\Agent;
use app\common\model\CardFans;
use app\common\model\CardGeneral;
use app\common\model\CardMember;
use app\common\model\Merchant;
use app\common\model\Momerchant;
use app\common\model\OpenTemplate;
use app\common\model\System;
use app\common\model\WxOpen;
use think\Log;
use think\Queue;
use think\queue\Job;
use think\Session;
use Wechat\Wxobjopen;

class Fans
{

    public function fire(Job $job, $data)
    {
//        switch ($data['type']){
//            //批量同步粉丝
//            case '1':
//                $isJobDone = $this->task_tpl_card($data);
//                break;
//            case '2':
//                $isJobDone = $this->task_syn_fans($data);
//                break;
////            default:
////                return "9003";
//        }
//        file_put_contents('/data2/html/payos/test.txt', 'fans-0' . json_encode($data), FILE_APPEND);
        $isJobDone = $this->task_syn_fans($data);
        $job->delete();

        if ($isJobDone) {
            //如果任务执行成功， 记得删除任务
            $job->delete();
            return '完成';
        } else {
            if ($job->attempts() > 3) {
                //通过这个方法可以检查这个任务已经重试了几次了
                print("<warn>任务已完成3次!" . "</warn>\n");
                $job->delete();
                // 也可以重新发布这个任务
                //print("<info>Hello Jobmach will be availabe again after 2s."."</info>\n");
                //$job->release(2); //$delay为延迟时间，表示该任务延迟2秒后再执行
            }
        }
    }



    /**
     * 根据消息中的数据进行实际的业务处理
     * @param array|mixed $data 发布任务时自定义的数据
     * @return boolean                 任务执行的结果
     */
    //批量同步粉丝
    public function task_syn_fans($data)
    {
        try{
//        file_put_contents('/data2/html/payos/test.txt', 'fans-2' . json_encode($data), FILE_APPEND);

//        return $data;
            //初始化微信类
            if (isset($data['gh_id'])) {
                $option = $this->options2($data['gh_id']);

                $wxObj = new Wxobjopen($option);
                $dataes['user_list'] = $data['openid'];
                $list = [];
                foreach ($data['openid'] as $v) {
                    $list['user_list'][] = array('openid' => $v, 'lang' => 'zh_CN');
                }

                $Fans = new CardFans();
                $fans = $wxObj->getUsersInfo($list);

                $datas = [];
                $datas2 = [];
                if ($fans) {

                    foreach ($fans['user_info_list'] as $k => $v) {
                        $sinfo = $Fans->where(array('openid' => $v['openid']))->find();
                        if ($sinfo) {
                            $datas[$k]['id'] = $sinfo['id'];
                            $datas[$k]['wx_open_id'] = $data['wx_open_id'];
                            $datas[$k]['gh_id'] = $data['gh_id'];
                            $datas[$k]['statu'] = $v['subscribe'];
                            $datas[$k]['openid'] = $v['openid'];
                            $datas[$k]['nickname'] = $v['nickname'];
                            $datas[$k]['sex'] = $v['sex'];
                            $datas[$k]['city'] = $v['city'];
                            $datas[$k]['head_url'] = $v['headimgurl'];
                            $datas[$k]['groupid'] = $v['groupid'];
                            $datas[$k]['create_time'] = $v['subscribe_time'];
                        } else {
                            $datas2[$k]['wx_open_id'] = $data['wx_open_id'];
                            $datas2[$k]['gh_id'] = $data['gh_id'];
                            $datas2[$k]['statu'] = $v['subscribe'];
                            $datas2[$k]['openid'] = $v['openid'];
                            $datas2[$k]['nickname'] = $v['nickname'];
                            $datas2[$k]['sex'] = $v['sex'];
                            $datas2[$k]['city'] = $v['city'];
                            $datas2[$k]['head_url'] = $v['headimgurl'];
                            $datas2[$k]['groupid'] = $v['groupid'];
                            $datas2[$k]['create_time'] = $v['subscribe_time'];
                        }
                    }

                }


                $Fans->allowField(true)->saveAll($datas);

                $Fans->allowField(true)->saveAll($datas2);

                return "成功";
            }
        }catch (\Exception $e){
            Log::write("task_syn_fans:".$e->getMessage() . $e->getFile() . ":" . $e->getLine(),'SysRunErrorLog');
        }
    }

    //微信API参数  根据card_id获取
    public function options($card_id)
    {
        //  Session::set('openid', null);
        $CardMember = new CardMember();
        $CardGeneral = new CardGeneral();
        $Merchant = new Merchant();
        $System = new System();
        $WxOpen = new WxOpen();
        $Agent = new Agent();
        $mid = $CardMember->where('card_id', $card_id)->value('mid');
        if ($mid) {
            $map['id'] = $mid;
        } else {
            $map['id'] = $CardGeneral->where('card_id', $card_id)->value('mid');
        }
        $merchantinfo = $Merchant->where($map)->field('wx_open_id,agent')->find();
        $mab['id'] = $merchantinfo['wx_open_id'];
        $config = $Agent->where(array('id' => $merchantinfo['agent']))->find();
//        $config = $System->where(array('id' => 1))->find();
        $users = $WxOpen->where($mab)->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        return $options;
    }

    public function options2($gh_id)
    {
        $System = new System();
        $WxOpen = new WxOpen();
        $Agent = new Agent();
        $mab['gh_id'] = $gh_id;
//        $config = $System->where(array('id' => 1))->find();
        $users = $WxOpen->where($mab)->find();
        $Merchant=new Merchant();
        $users2=$Merchant->where(array('wx_open_id' => $users['id']))->value('agent');
        $config = $Agent->where(array('id' =>$users2))->field('component_token,component_encodingaeskey,component_appid,component_appsecret,open_ticket')->find();

        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
        );
        return $options;
    }

}
